package admin;

import content.UserContent;
import entity.GroupsLocal;
import entity.GroupsLocalHome;
import entity.UsersLocal;
import entity.UsersLocalHome;
import helper.SimpleJSONArray;
import helper.SimpleJSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import transfer.Group;
import transfer.User;
import transfer.UserRole;

/**
 *
 * @author Oleh
 */
public class GroupOperation extends HttpServlet {

    public static final String actionParameter = "action";
    public static final String contentValue = "content";
    public static final String createValue = "create";
    public static final String changeValue = "change";
    public static final String filterParameter = "filter";
    public static final String nameParameter = "name";
    public static final String roleParameter = "role";
    public static final String usersParameter = "users";
    public static final String groupParameter = "group";
    public static final String idProperty = "id";
    public static final String firstProperty = "first";
    public static final String lastProperty = "last";
    public static final String splitter = ";";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter(actionParameter);
        if (contentValue.equals(action)) {
            processContentAction(request, response);
        }
        if (createValue.equals(action)) {
            processCreateAction(request, response);
        }
        if (changeValue.equals(action)) {
            processChangeAction(request, response);
        }
    }

    private void processContentAction(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filter = request.getParameter(filterParameter);
        System.out.println("filter = " + filter);
        Integer idRole = new Integer(filter);
        ArrayList users = UserContent.getAllUsersForRole(UserRole.instance(idRole));
        SimpleJSONArray array = new SimpleJSONArray();
        for (Iterator iterator = users.iterator(); iterator.hasNext();) {
            SimpleJSONObject userJSON = new SimpleJSONObject();
            User currentUser = (User) iterator.next();
            userJSON.addProperty(idProperty, currentUser.getIdUser().toString());
            userJSON.addProperty(firstProperty, currentUser.getFirstName());
            userJSON.addProperty(lastProperty, currentUser.getLastName());
            array.addElement(userJSON);
        }
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.print(array);
        out.flush();
        out.close();
    }

    private void processCreateAction(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter(nameParameter);
        String roleString = request.getParameter(roleParameter);
        String users = request.getParameter(usersParameter);
        Integer[] ids = null;
        if (users != null && !users.equals("")) {
            String[] userIds = users.split(splitter);
            ids = new Integer[userIds.length];
            for (int i = 0; i < ids.length; i++) {
                ids[i] = new Integer(userIds[i]);
            }
        }
        UserRole role = null;
        if (roleString != null && !roleString.equals("")) {
            role = UserRole.instance(new Integer(roleString));
        }
        try {
            InitialContext context = new InitialContext();
            GroupsLocalHome homeGroup = (GroupsLocalHome) context.lookup("java:comp/env/Groups");
            ArrayList groupUsers = new ArrayList();
            if (ids != null) {
                UsersLocalHome homeUsers = (UsersLocalHome) context.lookup("java:comp/env/Users");
                for (int i = 0; i < ids.length; i++) {
                    UsersLocal localUsers = homeUsers.findByPrimaryKey(ids[i]);
                    groupUsers.add(localUsers.getUser());
                }
            }
            if (role != null) {
                for (Iterator iterator = groupUsers.iterator(); iterator.hasNext();) {
                    User currentUser = (User) iterator.next();
                    ArrayList roles = currentUser.getRoles();
                    if (!roles.contains(role)) {
                        roles.add(role);
                    }
                }
            }
            Group group = new Group();
            group.setNameGroup(name);
            group.setUsers(groupUsers);
            homeGroup.create(group);
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (FinderException ex) {
            ex.printStackTrace();
        } catch (CreateException ex) {
            ex.printStackTrace();
        }
    }

    private void processChangeAction(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter(nameParameter);
        String roleString = request.getParameter(roleParameter);
        String users = request.getParameter(usersParameter);
        Integer idGroup = new Integer(request.getParameter(groupParameter));
        Integer[] ids = null;
        if (users != null && !users.equals("")) {
            String[] userIds = users.split(splitter);
            ids = new Integer[userIds.length];
            for (int i = 0; i < ids.length; i++) {
                ids[i] = new Integer(userIds[i]);
            }
        }
        UserRole role = null;
        if (roleString != null && !roleString.equals("")) {
            role = UserRole.instance(new Integer(roleString));
        }
        try {
            InitialContext context = new InitialContext();
            GroupsLocalHome homeGroup = (GroupsLocalHome) context.lookup("java:comp/env/Groups");
            ArrayList groupUsers = new ArrayList();
            if (ids != null) {
                UsersLocalHome homeUsers = (UsersLocalHome) context.lookup("java:comp/env/Users");
                for (int i = 0; i < ids.length; i++) {
                    UsersLocal localUsers = homeUsers.findByPrimaryKey(ids[i]);
                    groupUsers.add(localUsers.getUser());
                }
            }
            if (role != null) {
                for (Iterator iterator = groupUsers.iterator(); iterator.hasNext();) {
                    User currentUser = (User) iterator.next();
                    ArrayList roles = currentUser.getRoles();
                    if (!roles.contains(role)) {
                        roles.add(role);
                    }
                }
            }
            Group group = new Group();
            group.setIdGroup(idGroup);
            group.setNameGroup(name);
            group.setUsers(groupUsers);
            GroupsLocal groupLocal = homeGroup.findByPrimaryKey(idGroup);
            groupLocal.setGroup(group);
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (FinderException ex) {
            ex.printStackTrace();
        } 
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
